//
//  CreateCompanyVC.m
//  YaoHeAPP
//
//  Created by mac on 15/11/30.
//  Copyright (c) 2015年 mac. All rights reserved.
//

#import "CreateCompanyVC.h"
#import "Masonry.h"
#import "AFNetworking.h"
#import "Define.h"
#import "UIImageView+WebCache.h"
#import "AddImageBtn.h"
#import "WebVC.h"
#import "Controller.h"
#import "DatabaseTool.h"
#import "sheng.h"
#import "city.h"
#import "Tool.h"
#import "MyCell.h"
#import "ProvinceAndCity.h"
#import "QueryCompanyTableView.h"    
#import "TongYong.h"
#import "CompanyItemModel.h"
#import "MJExtension.h"

@interface CreateCompanyVC ()<UICollectionViewDataSource,UICollectionViewDelegate,UIScrollViewDelegate,UIAlertViewDelegate>
{
    UIImagePickerController*_imagePickerController;
    NSMutableDictionary*_shengCitydic;
    UICollectionView*_collectionView;
    UIImage*BUSINESS;//公司营业执照的图片路径
    UIImage*TAX;//公司税务登记证的图片路径
    UIImage*ORGANIZATION_CODE;//组织机构代码证的图片路径
    UIScrollView *scrollView;
}
@property(nonatomic,strong) QueryCompanyTableView *queryCompanyTableView;
@property(nonatomic,strong) NSArray *companyItemArray;
@property(nonatomic,strong) UISwitch *mySwitch;
@property(nonatomic,strong) UILabel *tishilabel;
@property(nonatomic,strong) UILabel*tishilabeltext;
@property(nonatomic,strong) UIButton*registBtn;
@property(nonatomic,strong) UIView *backView;//每个小的组合的背景View
@property(nonatomic,strong) UIView *bigView;//大的背景视图
@property (strong, nonatomic)  CompanyItemModel *companyItemModelData;//确认点击回来的数据
@end

@implementation CreateCompanyVC

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"CreateCompanyVC"];
    
    [[self rdv_tabBarController] setTabBarHidden:YES animated:YES];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"CreateCompanyVC"];
    
    [[self rdv_tabBarController] setTabBarHidden:NO animated:YES];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    scrollView.contentSize = CGSizeMake(self.view.frame.size.width,568);
    _bigView.frame=CGRectMake(0, 0, self.view.frame.size.width, 568);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _imageDic=[NSMutableDictionary dictionary];
    
    //    BUSINESS=[[UIImage alloc]init];
    //    TAX=[[UIImage alloc]init];
    //    ORGANIZATION_CODE=[[UIImage alloc]init];
    
    
    width=self.view.frame.size.width;
    height=self.view.frame.size.height;
    
    self.view.backgroundColor=bgVCcolor;
    //加一个导航条
    UIView*navcBar=[[UIView alloc]init];
    navcBar.backgroundColor=[UIColor colorWithRed:90.f/255.f green:191.f/255.f blue:219.f/255.f alpha:1];
    [self.view addSubview:navcBar];
    [self.view bringSubviewToFront:navcBar];
    [navcBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(0);   make.left.offset(0);
        make.height.offset(kNavigationBarHeight);  make.right.offset(0);
    }];
    
    //导航条标题
    UILabel*titleLabel=[[UILabel alloc]init];
    titleLabel.text=@"创建公司";
    titleLabel.font=Font(17);
    titleLabel.textAlignment=NSTextAlignmentCenter;
    titleLabel.textColor=[UIColor whiteColor];
    [navcBar addSubview:titleLabel];
    [titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(25);
        make.left.offset(width/2-50);
        make.width.offset(100);
        make.height.offset(30);
    }];
    
    //返回按钮
    UIButton*leftButton=[UIButton buttonWithType:UIButtonTypeCustom];
    [leftButton setBackgroundImage:[UIImage imageNamed:@"return"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [navcBar addSubview:leftButton];
    [leftButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(6);
        make.width.offset(24);
        make.height.offset(22);
        make.bottom.offset(-12);
    }];
    

    // 1.创建UIScrollView
    scrollView = [[UIScrollView alloc] init];
    scrollView.frame = CGRectMake(0, kNavigationBarHeight, self.view.frame.size.width, self.view.frame.size.height-kNavigationBarHeight); // frame中的size指UIScrollView的可视范围
    scrollView.delegate=self;
    [self.view addSubview:scrollView];
    
    _bigView=[[UIView alloc]init];
    
    _bigView.frame=CGRectMake(0, 0, self.view.frame.size.width, 568);
    [scrollView addSubview:_bigView];
    
    scrollView.contentSize =CGSizeMake(self.view.frame.size.width, 568);

    
    labelArray=[[NSArray alloc]initWithObjects:@"公司名称:",@"联系方式:",@"所在地:",@"详细地址:",nil];
    placeArray=[[NSArray alloc]initWithObjects:@"请输入营业执照上的名称",@"请输入联系方式",@"公司所在的省市",@"请输入公司的详细地址",nil];
    
    for (int i=0; i<4 ;i++)
    {
        _backView=[[UIView alloc]init];
        _backView.backgroundColor=[UIColor whiteColor];
        _backView.tag=10000+i;
        [_bigView addSubview:_backView];
        [_backView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.offset(i*51);
            make.left.offset(5);
            make.right.offset(-5);
            make.height.offset(50);
        }];
        
        //必填的内容前的星星图片
        UIImageView*startImage=[[UIImageView alloc]init];
        startImage.image=[UIImage imageNamed:@"bi_tian"];
        [_backView addSubview:startImage];
        [startImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.offset(17);
            make.left.offset(5);
            make.height.offset(16);
            make.width.offset(17);
        }];
        
        //提示标签
        UILabel*phone=[[UILabel alloc]init];
        phone.font=[UIFont systemFontOfSize:14];
        phone.text=labelArray[i];
        [_backView addSubview:phone];
        [phone mas_makeConstraints:^(MASConstraintMaker*make) {
            make.left.offset(28);
            make.top.offset(6);
            make.bottom.offset(-6);
            make.width.offset([self getTextwidthWithString:labelArray[i]]);
        }];
        
        
        //手机号输入框
        _phoneText=[[UITextField alloc]init];
        _phoneText.font=[UIFont systemFontOfSize:13];
        _phoneText.placeholder=placeArray[i];
        _phoneText.borderStyle=UITextBorderStyleNone;
        _phoneText.tag=100+i;
        
        if (i==0) {
        [_phoneText addTarget:self action:@selector(EditingChanged) forControlEvents:UIControlEventEditingChanged];
        }
        
        [_phoneText addTarget:self action:@selector(keyboardDissmiss) forControlEvents:UIControlEventEditingDidEndOnExit];
        [_backView addSubview:_phoneText];
        [_phoneText mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(phone.mas_right).offset(2);
            make.right.offset(-5);
            make.top.offset(5);
            make.bottom.offset(-5);
        }];
        
        if (i==2)
        {
            if ([[NSUserDefaults standardUserDefaults]objectForKey:@"NshengName"]==nil) {
                
            }
            else{
                NSString*City=[[NSUserDefaults standardUserDefaults]objectForKey:@"NcityName"];
                NSString*Sheng=[[NSUserDefaults standardUserDefaults]objectForKey:@"NshengName"];
                _phoneText.text=[NSString stringWithFormat:@"%@-%@",Sheng,City];
                sheng_ID=[ProvinceAndCity inputShengName:Sheng];
                city_ID =[ProvinceAndCity inputCityName:City];
            }
            
            shengCityBtn=[UIButton buttonWithType:UIButtonTypeCustom];
            shengCityBtn.backgroundColor=[UIColor clearColor];
            [shengCityBtn addTarget:self action:@selector(shengCityBtn) forControlEvents:UIControlEventTouchUpInside];
            [_backView addSubview:shengCityBtn];
            [shengCityBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.equalTo(phone.mas_right).offset(0);
                make.top.offset(0);
                make.right.offset(0);
                make.bottom.offset(0);
            }];
        }
    }
    
    //放置三证的背景View
    photoView=[[UIView alloc]init];
    photoView.backgroundColor=[UIColor whiteColor];
    [_bigView addSubview:photoView];
    photoView.frame=CGRectMake(5, 209, self.view.frame.size.width-10, 60);

    //三证上传这几个字的label
    UILabel*photoTxt=[[UILabel alloc]init];
    photoTxt.text=@"三证上传:";
    [photoView addSubview:photoTxt];
    [photoTxt mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(6);
        make.left.offset(28);
        make.height.offset(38);
        make.width.offset(80);
    }];
    
    
    //开关
    _mySwitch =[[UISwitch alloc]init];
    _mySwitch.frame =CGRectMake(width-70, 10, 0, 0);
    [_mySwitch setOn:NO animated:YES];
    [_mySwitch addTarget: self action:@selector(switchValueChanged:) forControlEvents:UIControlEventValueChanged];
    [photoView addSubview:_mySwitch];
    
    //提示
    _tishilabel=[[UILabel alloc]init];
    _tishilabel.font=Font(11);
    _tishilabel.text=@"提示:";
    _tishilabel.hidden=YES;
    _tishilabel.textColor=RGBCOLOR(251, 87, 60);
    _tishilabel.textAlignment=NSTextAlignmentLeft;
    _tishilabel.frame=CGRectMake(28,50,30,25);
    [photoView addSubview:_tishilabel];
    
    
    _tishilabeltext=[[UILabel alloc]init];
    _tishilabeltext.font=Font(11);
    _tishilabeltext.hidden=YES;
    _tishilabeltext.frame=CGRectMake(55,50,width-28-55,50);
    _tishilabeltext.text=@"工商营业执照、组织机构代码证和税务登记证三证尚未合成为一证的企业，请将三证都上传至平台。三证已合为一证，仅需上传营业执照。";
    _tishilabeltext.textColor=[UIColor grayColor];
    _tishilabeltext.textAlignment=NSTextAlignmentLeft;
    _tishilabeltext.numberOfLines=0;
    [photoView addSubview:_tishilabeltext];
    
    //表格布局加载图片
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    //设置单元格的大小
    layout.itemSize = CGSizeMake((width-42)/3,(width-42)/3);
    layout.minimumInteritemSpacing = 4;
    layout.minimumLineSpacing = 4;
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    //设置上下左右四个方向item距离边界的长度
    layout.sectionInset = UIEdgeInsetsMake(4, 4, 4, 4);
    _collectionView = [[UICollectionView alloc]initWithFrame:[[UIScreen mainScreen] bounds] collectionViewLayout:layout];
    //_collectionView默认背景颜色是黑色
    _collectionView.backgroundColor = [UIColor whiteColor];
    //设置数据源和代理
    _collectionView.dataSource  = self;
    _collectionView.delegate = self;
    [_collectionView registerNib:[UINib nibWithNibName:@"MyCell" bundle:nil] forCellWithReuseIdentifier:@"cell"];
    _collectionView.frame=CGRectMake(0, 50+60, width-10, (width-80)/3+20);
    _collectionView.hidden=YES;
    [photoView addSubview:_collectionView];
    
    NSArray*array=[NSArray arrayWithObjects:@"营业执照",@"税务登记证",@"组织机构代码",nil];
    for (NSInteger i=0; i<3; i++)
    {
        UILabel*txtLabel=[[UILabel alloc]init];
        txtLabel.font=[UIFont systemFontOfSize:14];
        txtLabel.text=array[i];
        txtLabel.tag=10+i;
        txtLabel.hidden=YES;
        txtLabel.textAlignment=NSTextAlignmentCenter;
        txtLabel.frame=CGRectMake(13+i*((width-80)/3+25),(width-80)/3+65+60,(width-90)/3,25);
        [photoView addSubview:txtLabel];
    }
    
    //立即创建按钮
    _registBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    [_registBtn setTitle:@"立即创建" forState:UIControlStateNormal];
    UIImage*loginOldImg=[UIImage imageNamed:@"loginbutton"];
    UIImage*loginNewImg=[loginOldImg stretchableImageWithLeftCapWidth:15 topCapHeight:0];
    [_registBtn setBackgroundImage:loginNewImg forState:UIControlStateNormal];
    [_registBtn addTarget:self action:@selector(registBtnAtion) forControlEvents:UIControlEventTouchUpInside];
    [_bigView addSubview:_registBtn];
    [_registBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(photoView.mas_bottom).offset(20);
        make.left.offset(50);
        make.right.offset(-50);
        make.height.offset(40);
    }];
    
    
    _shengCitydic=[[NSMutableDictionary alloc]init];
    _shengArray=[NSMutableArray array];
    _cityArray=[NSMutableArray array];
    _shengArray=[DatabaseTool querySheng];
    NSArray*arrayCity=[DatabaseTool queryCity];
    _cityArray=[DatabaseTool queryCity];
    
    NSString *shengid;//省ID、根据省ID找出对应的市，添加到数组中
    //遍历数组
    for (NSInteger i=0; i<arrayCity.count; i++)
    {
        city*city=arrayCity[i];
        shengid=city.shengID;
        if([[_shengCitydic allKeys] containsObject:shengid])
        {
            NSMutableArray*citys=[_shengCitydic valueForKey:shengid];
            [citys addObject:city];
        }
        else
        {
            NSMutableArray*citys=[NSMutableArray array];
            [citys addObject:city];
            [_shengCitydic setObject:citys forKey:shengid];
        }
    }
    
    //请求已经填写的公司名称
    [self requestCompany];
    
    
}

//请求已有的公司名称
-(void)requestCompany
{
    [Controller requestWithURL:PostQueryRemarkName jsondic:nil finishBlock:^(ClassData *classData) {
        
        if ([classData.number integerValue]==0) {
            
            UIView *find_view = (UIView *)[_bigView viewWithTag:10000];
            UITextField *find_Field = (UITextField *)[find_view viewWithTag:100];
            find_Field.text=classData.data[@"REMARK_NAME"];
        }
        else{
            ALERTSHOW(classData.message);
        }
    }];


}

//弹出一个View展示一个选择器让用户选择城市
-(void)shengCityBtn
{
    
    grayView=[[UIView alloc]initWithFrame:self.view.frame];
    grayView.backgroundColor=[UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.3];
    [self.view addSubview:grayView];
    [self.view bringSubviewToFront:grayView];
    //选择器的背景视图
    _selectView=[[UIView alloc]init];
    _selectView.frame=CGRectMake(20, height/2-(width-40)/2, width-40,(width-40)/1.5+35);
    _selectView.backgroundColor=[UIColor whiteColor];
    _selectView.layer.borderWidth=1;
    _selectView.layer.borderColor=[UIColor grayColor].CGColor;
    _selectView.layer.masksToBounds=YES;
    _selectView.layer.cornerRadius=10;
    [self.view addSubview:_selectView];
    //选择器的标题
    UILabel*titLab=[[UILabel alloc]init];
    titLab.frame=CGRectMake(0, 0, _selectView.frame.size.width, 30);
    titLab.text=@"城市选择";
    titLab.backgroundColor=[UIColor colorWithRed:206.f/255.f green:206.f/255.f blue:206.f/255.f alpha:1];
    titLab.textAlignment=NSTextAlignmentCenter;
    [_selectView addSubview:titLab];
    
    _shengCitydic=[[NSMutableDictionary alloc]init];
    _shengArray=[NSMutableArray array];
    _cityArray=[NSMutableArray array];
    _shengArray=[DatabaseTool querySheng];
    NSArray*arrayCity=[DatabaseTool queryCity];
    //_cityArray=[DatabaseTool queryCity];
    
    NSString *shengid;//省ID、根据省ID找出对应的市，添加到数组中
    //遍历数组
    for (NSInteger i=0; i<arrayCity.count; i++)
    {
        city*city=arrayCity[i];
        shengid=city.shengID;
        if([[_shengCitydic allKeys] containsObject:shengid])
        {
            NSMutableArray*citys=[_shengCitydic valueForKey:shengid];
            [citys addObject:city];
        }
        else
        {
            NSMutableArray*citys=[NSMutableArray array];
            [citys addObject:city];
            [_shengCitydic setObject:citys forKey:shengid];
        }
    }
    sheng*title=_shengArray[0];
    temp_sheng_ID = title.shengID;
    sheng_Name = title.shengName;
    [_cityArray  addObjectsFromArray:_shengCitydic[title.shengID]];
    city *currentCity =_cityArray[0];
    temp_city_ID = currentCity.cityID;
    city_Name = currentCity.cityName;
    
    //创建选择器
    pickView = [[UIPickerView alloc]init];
    pickView.frame = CGRectMake(0, 30, _selectView.frame.size.width,_selectView.frame.size.height-35-30);
    pickView.dataSource = self;
    pickView.delegate = self;
    [_selectView addSubview:pickView];
    
    //选择器上的取消按钮
    UIButton*button1=[UIButton buttonWithType:UIButtonTypeCustom];
    button1.backgroundColor=[UIColor whiteColor];
    [button1 setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    button1.frame=CGRectMake(0, _selectView.frame.size.height-35, _selectView.frame.size.width/2, 35);
    [button1 setTitle:@"取消" forState:UIControlStateNormal];
    button1.layer.borderWidth=1;
    [button1 addTarget:self action:@selector(qu_xiao) forControlEvents:UIControlEventTouchUpInside];
    [_selectView addSubview:button1];
    //选择器的确定按钮
    UIButton*button2=[UIButton buttonWithType:UIButtonTypeCustom];
    button2.backgroundColor=[UIColor whiteColor];
    button2.frame=CGRectMake(_selectView.frame.size.width/2, _selectView.frame.size.height-35, _selectView.frame.size.width/2, 35);
    [button2 setTitle:@"确定" forState:UIControlStateNormal];
    [button2 setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    button2.layer.borderWidth=1;
    [button2 addTarget:self action:@selector(que_ding) forControlEvents:UIControlEventTouchUpInside];
    [_selectView addSubview:button2];
    [pickView reloadAllComponents];
}

#pragma mark---------城市选择器的取消和确定按钮
-(void)qu_xiao
{
    [_selectView removeFromSuperview];
    [grayView removeFromSuperview];
}
-(void)que_ding
{
    sheng_ID = temp_sheng_ID;
    city_ID = temp_city_ID;
    UITextField*textField=(UITextField*)[self.view viewWithTag:102];
    NSString*string=[NSString stringWithFormat:@"%@-%@",sheng_Name,city_Name];
    textField.text=string;
    [_selectView removeFromSuperview];
    [grayView removeFromSuperview];
}

#pragma mark----------UIPickerView的协议方法
//有几列
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
}
//每列有多少行
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component==0)
    {
        return _shengArray.count;
    }
    return _cityArray.count;
}
//每个地方要显示的文字
-(UIView *) pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view

{
    if (component==0)
    {
        UIView *myView = [[UIView alloc]init];
        myView.frame =CGRectMake(0.0f, 0.0f, pickerView.frame.size.width, 40);
        UILabel *txtlabel = [[UILabel alloc] init];
        txtlabel.textAlignment = NSTextAlignmentCenter;
        txtlabel.frame = myView.frame;
        sheng*title=_shengArray[row];
        txtlabel.text = title.shengName;
        [myView addSubview:txtlabel];
        return myView;
    }
    UIView *myViewt=[[UIView alloc]init];
    myViewt.frame =CGRectMake(0, 0.0f, pickerView.frame.size.width, 40);
    UILabel *txtlabel2 = [[UILabel alloc] init];
    txtlabel2.textAlignment = NSTextAlignmentCenter;
    txtlabel2.frame = myViewt.frame;
    city*title=_cityArray[row];
    txtlabel2.text=title.cityName;
    [myViewt addSubview:txtlabel2];
    
    return myViewt;
    
}

//获去当前选中的是哪一行
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    
    //cityShengName=[[NSMutableArray alloc]init];
    if (component==0)
    {
        sheng*title=_shengArray[row];
        sheng_Name=title.shengName;
        temp_sheng_ID=title.shengID;
        [_cityArray removeAllObjects];
        [_cityArray addObjectsFromArray:_shengCitydic[temp_sheng_ID]];
        //城市
        city*titleC=_cityArray[0];
        city_Name=titleC.cityName;
        temp_city_ID=titleC.cityID;
        [pickerView reloadAllComponents];
        [pickerView selectRow:0 inComponent:1 animated:YES];
    }
    if (component==1)
    {
        city*title=_cityArray[row];
        city_Name=title.cityName;
        city_ID=title.cityID;
        temp_city_ID=title.cityID;
    }
}

//立即创建按钮
-(void)registBtnAtion
{
    [MobClick event:@"createNow"];
    
    UITextField*nameTag=(UITextField*)[self.view viewWithTag:100];
    UITextField*contactTag=(UITextField*)[self.view viewWithTag:101];
    UITextField*locitionTag=(UITextField*)[self.view viewWithTag:102];
    UITextField*detailLiTag=(UITextField*)[self.view viewWithTag:103];
    
    if (nameTag.text.length<=0)
    {
        ALERTSHOW(@"请输入公司名");
        return;
    }
    if (contactTag.text.length<=0)
    {
        ALERTSHOW(@"请输入联系方式");
        return;
    }
    if (locitionTag.text.length<=0)
    {
        ALERTSHOW(@"请输入地址");
        return;
    }
    if (detailLiTag.text.length<=0)
    {
        ALERTSHOW(@"请输入详细地址");
        return;
    }
    
    
    NSMutableDictionary *stringDic=[[NSMutableDictionary alloc]init];
    [stringDic setValue:nameTag.text forKey:@"COMPANY_NAME"];
    [stringDic setValue:sheng_ID forKey:@"ADDRESS_1"];
    [stringDic setValue:city_ID forKey:@"ADDRESS_2"];
    [stringDic setValue:detailLiTag.text forKey:@"DETAIL_ADDRESS"];
    [stringDic setValue:contactTag.text forKey:@"CONTACT_INFORMATION"];
    
      [Controller requestWithUrl:@"AppCompanyRegist/PostAddCompanyRecord?from=app" parameters:stringDic BUSINESS:BUSINESS TAX:TAX ORGANIZATION:ORGANIZATION_CODE finishBlock:^(ClassData *classData) {
        if ([classData.number integerValue]==0) {
            
            NSString *isregtype=@"10";
            [[NSUserDefaults standardUserDefaults] setObject:isregtype forKey:ISREGTYPE];
            
            NSString *IDnumString=@"123456";
            [[NSUserDefaults standardUserDefaults] setObject:IDnumString forKey:ISCREATE];
            UIAlertView*alertViewCT=[[UIAlertView alloc]initWithTitle:@"提示" message:@"你的信息已提交,我们会尽快给你答复" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            alertViewCT.tag=300;
            [alertViewCT show];
            
            //返回首页
            RootTabBarViewController *rootTabBarViewController = [RootTabBarViewController rootViewController];
            [rootTabBarViewController changeRootViewControllerTo:0];

        }
        else{
            ALERTSHOW(classData.message);
        }
        
    }];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return  3;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MyCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    if (indexPath.row==0) {
        if (BUSINESS==nil) {
            cell.clickRemove.hidden=YES;
            cell.addImage.hidden=NO;
            cell.Img.image=nil;
            cell.Img.layer.borderWidth=0.3;
            cell.Img.layer.borderColor=[UIColor lightGrayColor].CGColor;
        }
        else{
            cell.Img.hidden=NO;
            cell.clickRemove.hidden=NO;
            cell.addImage.hidden=YES;
            cell.Img.image=BUSINESS;
            [cell.clickRemove addTarget:self action:@selector(remove:) forControlEvents:UIControlEventTouchUpInside];
            cell.clickRemove.tag=indexPath.row;
        }
        
    }
    if (indexPath.row==1) {
        if (TAX==nil) {
            cell.clickRemove.hidden=YES;
            cell.addImage.hidden=NO;
            cell.Img.image=nil;
            cell.Img.layer.borderWidth=0.3;
            cell.Img.layer.borderColor=[UIColor lightGrayColor].CGColor;
        }
        else{
            cell.Img.hidden=NO;
            cell.clickRemove.hidden=NO;
            cell.addImage.hidden=YES;
            cell.Img.image=TAX;
            [cell.clickRemove addTarget:self action:@selector(remove:) forControlEvents:UIControlEventTouchUpInside];
            cell.clickRemove.tag=indexPath.row;
        }
        
    }
    if (indexPath.row==2) {
        if (ORGANIZATION_CODE==nil) {
            cell.clickRemove.hidden=YES;
            cell.addImage.hidden=NO;
            cell.Img.image=nil;
            cell.Img.layer.borderWidth=0.3;
            cell.Img.layer.borderColor=[UIColor lightGrayColor].CGColor;
        }
        else{
            cell.Img.hidden=NO;
            cell.clickRemove.hidden=NO;
            cell.addImage.hidden=YES;
            cell.Img.image=ORGANIZATION_CODE;
            [cell.clickRemove addTarget:self action:@selector(remove:) forControlEvents:UIControlEventTouchUpInside];
            cell.clickRemove.tag=indexPath.row;
        }
        
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍照" otherButtonTitles:@"从相册选择", nil];
    [sheet showInView:self.view];
    btnTag=indexPath.row;
}
//移除图片的方法
-(void)remove:(UIButton*)btn
{
    if (btn.tag==0) {
        BUSINESS=nil;
        [_collectionView reloadData];
    }
    if (btn.tag==1) {
        TAX=nil;
        [_collectionView reloadData];
    }
    if (btn.tag==2) {
        ORGANIZATION_CODE=nil;
        [_collectionView reloadData];
    }
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    //拍照
    if (buttonIndex== 0) {
        
        BOOL isCamera = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
        if(!isCamera)
        {
            ALERTSHOW(@"无法调用相机,请检查系统设置");
            return;
        }
        _imagePickerController = [[UIImagePickerController alloc] init];
        _imagePickerController.sourceType= UIImagePickerControllerSourceTypeCamera;
        _imagePickerController.delegate=self;
        //编辑模式
        _imagePickerController.allowsEditing= YES;
        [self presentViewController:_imagePickerController animated:YES completion:nil];
        
    }
    else if (buttonIndex == 1) {
        //从相册选择
        _imagePickerController= [[UIImagePickerController alloc] init];
        //设置picker类型
        _imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        //设置代理
        _imagePickerController.delegate = self;
        //设置图片可以修改
        _imagePickerController.allowsEditing = YES;
        [self presentViewController:_imagePickerController animated:YES completion:nil];
    }
}

#pragma mark - UIIMAGE PICKER DELEGATE
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    if(picker.sourceType == UIImagePickerControllerSourceTypeCamera)
    {
        NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
        if ([type isEqualToString:@"public.image"]) {
            if (btnTag==0) {
                BUSINESS=[info objectForKey:UIImagePickerControllerEditedImage];
                UIImageWriteToSavedPhotosAlbum(BUSINESS, self,
                                               @selector(image:didFinishSavingWithError:contextInfo:),
                                               nil);
                
                [_collectionView reloadData];
            }
            if (btnTag==1) {
                TAX=[info objectForKey:UIImagePickerControllerEditedImage];
                UIImageWriteToSavedPhotosAlbum(TAX, self,
                                               @selector(image:didFinishSavingWithError:contextInfo:),
                                               nil);
                [_collectionView reloadData];
                
            }
            if (btnTag==2) {
                ORGANIZATION_CODE=[info objectForKey:UIImagePickerControllerEditedImage];
                UIImageWriteToSavedPhotosAlbum(ORGANIZATION_CODE, self,
                                               @selector(image:didFinishSavingWithError:contextInfo:),
                                               nil);
                [_collectionView reloadData];
            }
        }
    }
    else{
        [_imagePickerController dismissViewControllerAnimated:YES completion:^{
            if (btnTag==0) {
                BUSINESS=[info objectForKey:UIImagePickerControllerEditedImage];
                UIImageWriteToSavedPhotosAlbum(BUSINESS, self,
                                               @selector(image:didFinishSavingWithError:contextInfo:),
                                               nil);
                [_collectionView reloadData];
            }
            if (btnTag==1) {
                TAX=[info objectForKey:UIImagePickerControllerEditedImage];
                UIImageWriteToSavedPhotosAlbum(TAX, self,
                                               @selector(image:didFinishSavingWithError:contextInfo:),
                                               nil);
                [_collectionView reloadData];
            }
            if (btnTag==2) {
                ORGANIZATION_CODE=[info objectForKey:UIImagePickerControllerEditedImage];
                UIImageWriteToSavedPhotosAlbum(ORGANIZATION_CODE, self,
                                               @selector(image:didFinishSavingWithError:contextInfo:),
                                               nil);
                [_collectionView reloadData];
            }
        }];
    }
}

//点击相册页面的取消按钮返回
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [_imagePickerController dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 照片保存后
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    if (!error) {
        [_imagePickerController dismissViewControllerAnimated:YES completion:^{
            if (btnTag==0) {
                BUSINESS=image;
                [_collectionView reloadData];
            }
            if (btnTag==1) {
                TAX=image;
                [_collectionView reloadData];
            }
            if (btnTag==2) {
                ORGANIZATION_CODE=image;
                [_collectionView reloadData];
            }
        }];
    }
}

//警告框的协议方法 下方两个按钮的索引
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag==200) {
        RootTabBarViewController *rootTabBarViewController = [RootTabBarViewController rootViewController];
        [rootTabBarViewController changeRootViewControllerTo:0];
    }
    if (alertView.tag==300) {
        RootTabBarViewController *rootTabBarViewController = [RootTabBarViewController rootViewController];
        [rootTabBarViewController changeRootViewControllerTo:0];
    }
    
    if (alertView.tag==20) {
        if (buttonIndex==0) {
            //取消
        }else if (buttonIndex==1){
            //加入公司
            NSDictionary*dic=@{@"MEMBER_ID":_companyItemModelData.COMPANY_ID};
            [Controller requestWithURL:PostApplyForCompany jsondic:dic finishBlock:^(ClassData *classData) {
                if ([classData.number integerValue]==0) {
                    ALERTSHOW(@"成功加入该公司");
                    //返回首页
                    RootTabBarViewController *rootTabBarViewController = [RootTabBarViewController rootViewController];
                    [rootTabBarViewController changeRootViewControllerTo:0];

                }else{
                    ALERTSHOW(classData.message);
                }
            }];
            
            
            
        }
    }

    
}

//返回上一层
-(void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

//计算文字宽度（设置label的高度）
-(NSInteger)getTextwidthWithString:(NSString *)string
{
    CGRect rect = [string boundingRectWithSize:CGSizeMake(MAXFLOAT,38) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:15]} context:nil];
    return rect.size.width+8;
}

//键盘弹下
-(void)keyboardDissmiss
{
    return;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


- (void) switchValueChanged:(id)sender{
    UISwitch* control = (UISwitch*)sender;
    if(control ==_mySwitch){
        BOOL on = control.on;
        //添加自己要处理的事情代码(on 是开关状态)
        if (on==YES) {
            
            photoView.frame=CGRectMake(5, 209, self.view.frame.size.width-10, (width-42)/3+150);
            
            for (NSInteger i=0; i<3; i++)
            {
                UILabel *find_label = (UILabel *)[photoView viewWithTag:10+i];
                find_label.hidden=NO;
            }
            _tishilabeltext.hidden=NO;
            _tishilabel.hidden=NO;
            _collectionView.hidden=NO;
            
        }else if(on==NO){
            
            photoView.frame=CGRectMake(5, 209, self.view.frame.size.width-10, 60);
            
            for (NSInteger i=0; i<3; i++)
            {
                UILabel *find_label = (UILabel *)[photoView viewWithTag:10+i];
                find_label.hidden=YES;
            }
            _tishilabeltext.hidden=YES;
            _tishilabel.hidden=YES;
            _collectionView.hidden=YES;
            
        }
        
        [_registBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(photoView.mas_bottom).offset(20);
            make.left.offset(50);
            make.right.offset(-50);
            make.height.offset(40);
        }];
        
    }
}


//改变输入框的内容的时候调用的方法
-(void)EditingChanged
{
    
    UIView *find_view = (UIView *)[_bigView viewWithTag:10000];
    
    UITextField *find_Field = (UITextField *)[find_view viewWithTag:100];
    
    if (![TongYong isBlankObjectAndStr:find_Field.text]) {
        //调取查找相关公司的名称 //进行查询
        [self queryCopmany];
    }else{
     [_queryCompanyTableView removeFromSuperview];
    }
}

//公司名称模糊查询
-(void)queryCopmany
{
    
    UIView *find_view = (UIView *)[_bigView viewWithTag:10000];
    
    UITextField *find_Field = (UITextField *)[find_view viewWithTag:100];
    
    NSDictionary*dic=@{@"COMPANY_NAME":find_Field.text};
    [Controller requestWithURL:PostlikelyCompanyName jsondic:dic finishBlock:^(ClassData *classData) {
        
        if ([classData.number integerValue]==0) {
            
            _companyItemArray = [CompanyItemModel mj_objectArrayWithKeyValuesArray:classData.data];
            
            if (_companyItemArray.count==0) {
                
                [_queryCompanyTableView removeFromSuperview];
                
            }else{
                
                [self.view addSubview:self.queryCompanyTableView];
                [self.queryCompanyTableView bringToFront];
                self.queryCompanyTableView.QueryCompanyList =_companyItemArray;
                [self.queryCompanyTableView reloadData];
                
            }
            
        }
        else{
            ALERTSHOW(classData.message);
        }
    }];
    
    
}

- (QueryCompanyTableView *)queryCompanyTableView {
    
    if (!_queryCompanyTableView) {
        _queryCompanyTableView = [[QueryCompanyTableView alloc] initWithFrame:CGRectMake(0, 110, SCREEN_WIDTH, 350) style:UITableViewStylePlain ];
        __block CreateCompanyVC *weakSelf = self;
        _queryCompanyTableView.cancelActionBlock = ^() {
            [weakSelf closeIt];
        };
        
        _queryCompanyTableView.didSelectRowBlock = ^(NSInteger indexPathRow) {
            weakSelf.companyItemModelData = weakSelf.companyItemArray[indexPathRow];
            NSString *mesagest=[NSString stringWithFormat:@"%@",weakSelf.companyItemModelData.COMPANY_NAME];
            UIView *find_view = (UIView *)[weakSelf.bigView viewWithTag:10000];
            UITextField *find_Field = (UITextField *)[find_view viewWithTag:100];
            find_Field.text=mesagest;
            UIAlertView *alertViewCT=[[UIAlertView alloc]initWithTitle:@"加入公司" message:mesagest delegate:weakSelf cancelButtonTitle:@"取消" otherButtonTitles:@"加入", nil];
            alertViewCT.tag=20;
            [alertViewCT show];
            
            [weakSelf closeIt];
            
        };
    }
    return _queryCompanyTableView;
}
-(void)closeIt
{
    [_queryCompanyTableView removeFromSuperview];
    
}



/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
